package com.ctrip.corp.obt.shard.context;

import com.ctrip.corp.obt.generic.core.context.RequestContext;

import static com.ctrip.corp.obt.generic.constants.GenericConstants.TENANT_ID;

public class DataShardContext {

    private static final String ALLOW_TABLE_REROUTE = "allowTableReroute";
    private static final String TB_SHARD_SOURCE = "tbShardSource";
    private static final String DB_SHARD_SOURCE = "dbShardSource";

    /**
     * TODO pending remove
     * @param tenantId
     */
    public static void setTenantId(String tenantId) {
        addContextParams(TENANT_ID, tenantId);
    }

    /**
     * TODO pending remove
     */
    public static void clearTenantId() {
        RequestContext.getCurrentContext().unsetContextParams(TENANT_ID);
    }

    public static void clearDBShardSource() {
        RequestContext.getCurrentContext().unsetContextParams(DB_SHARD_SOURCE);
    }

    public static Boolean isAllowTableReroute() {
        return null == getContextParams(ALLOW_TABLE_REROUTE) ? Boolean.FALSE : (Boolean) getContextParams(ALLOW_TABLE_REROUTE);
    }

    public static void allowTableReroute() {
        addContextParams(ALLOW_TABLE_REROUTE, Boolean.TRUE);
    }


    public static String getTableShardSource() {
        return (String) getContextParams(TB_SHARD_SOURCE);
    }

    public static void setTableShardSource(String shardSource) {
        addContextParams(TB_SHARD_SOURCE, shardSource);
    }

    public static String getDBShardSource() {
        return (String) getContextParams(DB_SHARD_SOURCE);
    }

    public static void setDBShardSource(String shardSource) {
        addContextParams(DB_SHARD_SOURCE, shardSource);
    }

    private DataShardContext() {
    }

    private static Object getContextParams(String contextParamKey) {
        return RequestContext.getCurrentContext().getContextParams(contextParamKey);
    }

    private static void addContextParams(String contextParamKey, Object contextParamValue) {
        RequestContext.getCurrentContext().addContextParams(contextParamKey, contextParamValue);
    }

}
